--为了减少文件名重复，增加一个随机数
math.randomseed(os.time())

function file_exists(path)
  local file = io.open(path, "rb")
  if file then file:close() end
  return file ~= nil
end
ngx.update_time()
--设定临时文件的目录，设置在tmp目录下，可以随时的进行清理
tPath = "/tmp/vdisk_ts/"
if file_exists(tPath) == false
then
   os.execute("mkdir -p "..tPath)
end
local bt = ngx.now()*1000
ngx.log(ngx.DEBUG, "begin:", bt)

local base_m3u8_url = "/proxyts"..ngx.var.uri:gsub("/ts2ts/","/")
local base_ts_url = base_m3u8_url:gsub("mts", "ts")

ngx.print(base_ts_url)
local res = ngx.location.capture(base_ts_url)
ngx.update_time()
local ct = ngx.now()*1000
ngx.log(ngx.DEBUG, "ct:", ct)
local filename = tPath..tostring(ct)..".tmp"
ngx.log(ngx.DEBUG, "filename:"..filename)
local file = io.open(filename, "wb");
file:write(res.body)
file:close()
local ntsfile = filename..".ts"
local cmd = "ffmpeg -i "..filename.." -vcodec h264 -acodec aac -s 1280x720 -crf 26 -b:v 300k -profile main -preset fast -r 25 -ar 44100 -ab 16k -strict -2 "..ntsfile
os.execute(cmd)
local file1 = io.open(ntsfile, "r")
local nbody = file1:read("*a")
file1:close()
os.remove(filename)
os.remove(ntsfile)
ngx.print(nbody)
ngx.update_time()
local et = ngx.now()*1000

ngx.log(ngx.DEBUG, "end:", et)
ngx.exit(ngx.HTTP_OK)
